<template>
  <l-layout class="l-tab-page" v-show="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("功能分类") }}
          <div class="tree-setting-btn">
            <el-tooltip effect="dark" content="分类管理" placement="top">
              <el-button @click="handleSettingClick" type="text" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </div>
        </template>
        <el-tree
          ref="tree"
          node-key="id"
          :highlight-current="true"
          :data="dataItemTree_Function"
          @node-click="handleNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node }">
            <i class="el-icon-notebook-2"></i>
            {{ node.label }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入功能名称')"
            @keyup.enter.native="hanleSearch"
            v-model="searchWord"
            size="mini"
          >
            <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()">
          <el-button-group>
            <el-button type="primary" size="mini" @click="handleCAdd()">新增自已定义表单功能</el-button>
          </el-button-group>
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table :columns="columns" :dataSource="tableShowData" :loading="loading">
        <template v-slot:f_Type="scope">
          {{ lr_dataItemName(lr_dataItem["function"], scope.row.f_Type) }}
        </template>
        <template v-slot:f_IsSystem="scope">
          <el-tag v-if="scope.row.f_IsSystem === 1" size="mini">代码开发</el-tag>
          <el-tag v-else-if="scope.row.f_IsSystem === 3 || scope.row.f_IsSystem === 4" size="mini" type="warning"
            >移动桌面</el-tag
          >
          <el-tag v-else size="mini" type="success">自定义表单</el-tag>
        </template>
        <template v-slot:f_EnabledMark="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.f_EnabledMark"
            @change="handleEnableChange(scope.row)"
          >
          </el-switch>
        </template>
        <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick"></l-table-btns>
      </l-table>
    </l-panel>

    <l-dialog
      :title="formTitle"
      :visible.sync="formVisible"
      :height="464"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <my-form ref="form"></my-form>
    </l-dialog>

    <l-drawer :title="$t('分类管理')" :visible.sync="classifysVisible" :showOk="false" :showClose="false" size="800px">
      <l-dataitem-index classifyCode="function"></l-dataitem-index>
    </l-drawer>

    <l-fullscreen-dialog
      :title="`${$t('功能设计')}`"
      :headerMidWidth="320"
      :visible.sync="cformVisible"
      :isStep="true"
      :steps="['基本配置', '页面设计']"
      :stepActive.sync="stepActive"
      :validateSteps="handleValidateSteps"
      @ok="handleCSave"
      @closed="handleCClosed"
      @opened="handleCOpened"
    >
      <c-my-form ref="cform" :stepActive="stepActive"></c-my-form>
    </l-fullscreen-dialog>

    <!--桌面设计-->
    <l-fullscreen-dialog
      :title="$t(formTitle)"
      :headerMidWidth="320"
      :visible.sync="deskVisible"
      :isStep="true"
      :steps="['基本配置', '桌面设计']"
      :stepActive.sync="deskStepActive"
      :validateSteps="handleDeskValidateSteps"
      @ok="handleDeskSave"
      @closed="handleDeskCloseForm"
      @opened="handleDeskOpenedForm"
    >
      <desk-form ref="deskform" :stepActive="deskStepActive"> </desk-form>
    </l-fullscreen-dialog>
  </l-layout>
</template>

<script>
const api = window.$api.mapp.module;
const apiDesktop = window.$api.desktop.setting;
import MyForm from "./form";
import CMyForm from "./cform";

import DeskForm from "../homeSetting/form.vue";
export default {
  components: {
    MyForm,
    CMyForm,
    DeskForm,
  },
  data() {
    return {
      lr_isPage: true,
      // 左侧树形
      treeCategory: "",
      classifysVisible: false,

      //查询
      searchWord: "",
      searchTableData: null,

      loading: false,
      columns: [
        { label: "名称", prop: "f_Name", minWidth: "110" },
        { label: "分类", prop: "f_Type", width: "120" },
        { label: "类型", prop: "f_IsSystem", width: "100", align: "center" },
        { label: "排序", prop: "f_SortCode", width: "64", align: "center" },
        { label: "状态", prop: "f_EnabledMark", width: "64", align: "center" },
      ],
      tableBtns: [
        { prop: "Edit", label: "编辑" },
        { prop: "Delete", label: "删除" },
      ],
      tableData: [],
      tableShowData: [],

      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,

      cformVisible: false,
      stepActive: 0,

      deskVisible: false,
      deskStepActive: 0,
      deskId: "",
    };
  },
  computed: {
    dataItemTree_Function() {
      return this.lr_dataItemTree(this.lr_dataItem["function"]);
    },
  },
  mounted() {
    this.lr_loadDataItem("function");
    this.loadTableData();
  },
  methods: {
    handleSettingClick() {
      this.classifysVisible = true;
    },
    handleNodeClick(node) {
      this.treeCategory = node.value;
      this.searchWord = "";
      this.tableShowData = this.tableData.filter((item) => item.f_Type == this.treeCategory);
    },

    async loadTableData() {
      this.loading = true;
      this.searchWord = "";
      const data = await this.$awaitWraper(api.getList());
      this.loading = false;
      this.tableData = data || [];
      this.tableShowData = this.tableData;
    },

    hanleSearch() {
      if (this.$validatenull(this.searchWord)) {
        this.tableShowData = this.tableData;
      } else {
        this.tableShowData = this.tableData.filter((t) => t.f_Name.indexOf(this.searchWord) != -1);
      }
    },
    async handleEnableChange(row) {
      if (row.f_IsSystem == 3 || row.f_IsSystem == 4) {
        await apiDesktop.updateStateByModuleId(row.f_Id, row.f_EnabledMark);
      } else {
        await api.updateState(row.f_Id, row.f_EnabledMark);
      }

      this.$message({
        type: "success",
        message: "更新成功!",
      });
    },
    handleAdd() {
      this.formEdit = false;
      this.showForm("新增移动功能");
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;

      if (row.f_IsSystem == 2) {
        this.cformVisible = true;
      } else if (row.f_IsSystem == 3 || row.f_IsSystem == 4) {
        this.formTitle = `编辑移动桌面-${row.f_Name}`;
        this.deskVisible = true;
      } else {
        this.showForm("编辑移动功能");
      }
    },
    handleDelete($index, row) {
      this.$confirm(this.$t("此操作将永久删除该数据, 是否继续?"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      })
        .then(async () => {
          if (row.f_IsSystem == 3 || row.f_IsSystem == 4) {
            apiDesktop.removeByModuleId(row.f_Id);
          } else {
            await api.remove(row.f_Id);
          }

          this.tableShowData.splice($index, 1);
          let index = this.tableData.findIndex((t) => t.f_Id == row.f_Id);
          if (index != -1) {
            this.tableData.splice(index, 1);
          }

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSave(showLoading, hideLoading) {
      this.$refs.form.validateForm(async () => {
        showLoading();
        const postData = this.$refs.form.getForm();
        if (this.formEdit) {
          // 修改数据
          if (await this.$awaitWraper(api.update(this.formEditRow.f_Id, postData))) {
            this.$message({
              type: "success",
              message: "更新成功!",
            });
            this.loadTableData();
            this.formVisible = false;
          }
        } else {
          // 新增数据
          if (await this.$awaitWraper(api.add(postData))) {
            this.$message({
              type: "success",
              message: "新增成功!",
            });
            this.loadTableData();
            this.formVisible = false;
          }
        }
        hideLoading();
      });
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        const data = await this.$awaitWraper(api.get(this.formEditRow.f_Id));
        this.$refs.form.setForm(data);
        hideLoading();
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },

    // 自定义表单设计
    handleCAdd() {
      this.formEdit = false;
      this.cformVisible = true;
    },

    handleValidateSteps() {
      return this.$refs.cform.validateSteps();
    },
    handleCSave(showLoading, hideLoading) {
      showLoading("保存数据中...");
      const postData = this.$refs.cform.getForm();
      if (this.formEdit) {
        api
          .update(this.formEditRow.f_Id, postData)
          .then(() => {
            this.loadTableData();
            this.$message({
              type: "success",
              message: "更新成功!",
            });
            this.cformVisible = false;
            hideLoading();
          })
          .catch(() => {
            hideLoading();
          });
      } else {
        api
          .add(postData)
          .then(() => {
            this.loadTableData();
            this.$message({
              type: "success",
              message: "保存成功!",
            });
            this.cformVisible = false;
            hideLoading();
          })
          .catch(() => {
            hideLoading();
          });
      }
    },
    handleCClosed() {
      this.$refs.cform.resetForm();
    },
    async handleCOpened(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        const data = await this.$awaitWraper(api.get(this.formEditRow.f_Id));

        this.$refs.cform.setForm(data.functionEntity);
        hideLoading();
      }
    },

    handleDeskValidateSteps() {
      return this.$refs.deskform.validateSteps();
    },
    handleDeskSave() {
      const loading = this.$loading({
        lock: true,
        text: "正在保存配置，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.2)",
      });

      this.$nextTick(async () => {
        const postData = await this.$refs.deskform.getForm();
        const res = await this.$awaitWraper(apiDesktop.update(this.deskId, postData));
        if (res) {
          this.$message({
            type: "success",
            message: "编辑成功!",
          });
          this.deskVisible = false;
          this.loadTableData();
        }
        loading.close();
      });
    },
    handleDeskCloseForm() {
      this.$refs.deskform.resetForm();
    },
    async handleDeskOpenedForm(showLoading, hideLoading) {
      showLoading("加载数据中...");
      const data = await this.$awaitWraper(apiDesktop.getByModuleId(this.formEditRow.f_Id));
      this.deskId = data.lr_desktop_infoEntity.f_Id;
      this.$refs.deskform.setForm(data);
      hideLoading();
    },
  },
};
</script>
